#include "uart.h"
#include "stdio.h"

static uint8_t aaa[10]="uart3 on\r\n";
dma_single_data_parameter_struct dma_init_struct;
void UART3_Init(void){
    /* enable DMA0 */
    rcu_periph_clock_enable(RCU_DMA0);
    /* deinitialize DMA channel7(USART0 tx) */
    dma_deinit(DMA0, DMA_CH4);
    dma_init_struct.direction = DMA_MEMORY_TO_PERIPH;
    dma_init_struct.memory0_addr = (uint32_t)aaa;
    dma_init_struct.memory_inc = DMA_MEMORY_INCREASE_ENABLE;
    dma_init_struct.periph_memory_width = DMA_PERIPH_WIDTH_8BIT;
    dma_init_struct.number = 10;
    dma_init_struct.periph_addr = (uint32_t)&USART_DATA(UART3);
    dma_init_struct.periph_inc = DMA_PERIPH_INCREASE_DISABLE;
    dma_init_struct.priority = DMA_PRIORITY_ULTRA_HIGH;
    dma_single_data_mode_init(DMA0, DMA_CH4, &dma_init_struct);
    /* configure DMA mode */
    dma_circulation_disable(DMA0, DMA_CH4);
    dma_channel_subperipheral_select(DMA0, DMA_CH4, DMA_SUBPERI4);
    /* enable DMA channel7 */
    dma_channel_enable(DMA0, DMA_CH4);

    /* USART DMA enable for transmission and reception */
    
    /* USART configure */
    rcu_periph_clock_enable(RCU_UART3);
    usart_deinit(UART3);
    usart_baudrate_set(UART3, 1000000);
    usart_word_length_set(UART3,USART_WL_8BIT);
    usart_parity_config(UART3,USART_PM_NONE);
    usart_stop_bit_set(UART3,USART_STB_1BIT);
    usart_hardware_flow_rts_config(UART3,USART_RTS_DISABLE);
    usart_hardware_flow_cts_config(UART3, USART_CTS_DISABLE);
    //usart_receive_config(UART3, USART_RECEIVE_ENABLE);
    usart_transmit_config(UART3, USART_TRANSMIT_ENABLE);
    usart_enable(UART3);
    usart_dma_transmit_config(UART3, USART_DENT_ENABLE);
}

int _write(int file, char *ptr, int len)
{
    while(RESET == dma_flag_get(DMA0, DMA_CH4, DMA_FLAG_FTF));
        //return len;
    dma_flag_clear(DMA0, DMA_CH4, DMA_FLAG_FTF);
    dma_channel_disable(DMA0, DMA_CH4);
    DMA_CHM0ADDR(DMA0,DMA_CH4) = (uint32_t)ptr;;
    DMA_CHCNT(DMA0,DMA_CH4) = len;
    dma_channel_enable(DMA0, DMA_CH4);
    //usart_dma_transmit_config(UART3, USART_DENT_ENABLE);
    return len;
}